package com.aifund.app.service.impl;

import com.aifund.app.service.OssService;
import com.aifund.common.enums.CommonEnum;
import com.aifund.common.enums.config.ConfigEnum;
import com.aifund.common.exception.AiFundException;
import com.aifund.common.result.ResultBody;
import com.aifund.common.service.SystemConfigService;
import com.aifund.common.util.FileUtil;
import io.minio.MinioClient;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.xmlpull.v1.XmlPullParserException;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    @Autowired
    MinioClient minioClient;
    @Autowired
    SystemConfigService systemConfigService;

    @Override
    public String uploadImg(MultipartFile file) {
        String contentType = file.getContentType();
        if(!FileUtil.isImage(FileUtil.convert(file))){
            throw new AiFundException("505","请上传图片");
        }
        // 检查存储桶是否已经存在
        boolean isExist = false;
        try {
            isExist = minioClient.bucketExists("aifund-system");
            if(isExist) {
                System.out.println("Bucket already exists.");
            } else {
                // 创建一个名为asiatrip的存储桶，用于存储照片的zip文件。
                minioClient.makeBucket("aifund-system");
            }
            // 使用putObject上传一个文件到存储桶中。
            String objectName = UUID.randomUUID().toString();
            InputStream inputStream = file.getInputStream();
            minioClient.putObject("aifund-system", objectName,inputStream,inputStream.available(),contentType);
            System.out.println("上传成功:"+objectName);
            String baseUrl = systemConfigService.getByKey(ConfigEnum.FILE_BASE_URL.getConfigKey()).getConfigValue();
            return baseUrl+objectName;
        }
        catch (MinioException e) {
            e.printStackTrace(); }
        catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }
        return null;
    }
}
